package com.atguigu.juc.chap02;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Taeyang
 * @date 2025/3/31
 */
public class LockDowngradingDemo01 {

    /**
     * 读写锁
     */
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 读锁
     */
    private final Lock readLock = lock.readLock();

    /**
     * 写锁
     */
    private final Lock writeLock = lock.writeLock();

    /**
     * 正确地锁降级：读锁写锁的获取和释放相互交叉，防止释放写锁与获取读锁之间的真空期之间有其他线程插入
     */
    public void test() {

        writeLock.lock();
        System.out.println("获取到写锁。。。。");

        // 写数据

        readLock.lock();
        System.out.println("获取到读锁----------");

        writeLock.unlock();
        System.out.println("释放写锁==============");

        // 读数据
        // 可以插入其他的读线程（因为读读可并发），从而提高应用程序的执行效率

        readLock.unlock();
        System.out.println("释放读锁++++++++++++++++");
    }
}
